<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>号源管理</title>

    <!-- 引入 Bootstrap CSS -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入 Font Awesome 图标 -->
    <link href="/css/all.min.css" rel="stylesheet">
    <!-- 引入 Bootstrap Datepicker CSS -->
    <link href="/css/bootstrap-datepicker.min.css" rel="stylesheet">

    <style>
        body {
            padding-top: 2rem;
            background-color: #f8f9fa;
        }
        .container {
            max-width: 1200px;
        }
        .action-buttons button {
            margin-right: 5px;
        }
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        .status-active {
            background: rgba(40, 167, 69, 0.1);
            color: #28a745;
        }
        .status-inactive {
            background: rgba(220, 53, 69, 0.1);
            color: #dc3545;
        }
        .table-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        .header-container {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
        }
        .filter-container {
            margin-bottom: 1.5rem;
            background: white;
            padding: 1rem;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }
        .period-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
            background: rgba(0, 123, 255, 0.1);
            color: #007bff;
        }
        .datepicker {
            z-index: 1000 !important; /* 确保日期选择器显示在最上层 */
        }
    </style>
</head>
<body>

<div class="container">

    <div class="header-container">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
                <h2 class="mb-0"><i class="fas fa-calendar-check me-2"></i>号源管理</h2>
                <p class="text-muted mb-0">管理医院医生号源信息</p>
            </div>
            <div>
                <button class="btn btn-primary me-2" onclick="location.href='/admins/addSchedule'">
                    <i class="fas fa-plus me-1"></i>添加号源
                </button>
                <button class="btn btn-outline-secondary" id="refreshBtn">
                    <i class="fas fa-sync-alt me-1"></i>刷新数据
                </button>
            </div>
        </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-container">
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label">科室</label>
                <div class="position-relative">
                    <input type="text" id="departmentFilter" class="form-control" placeholder="输入科室名称">
                    <div id="departmentSuggestions" class="position-absolute z-10 w-full bg-white border border-gray-300 rounded-b-lg shadow-lg max-h-60 overflow-y-auto d-none"></div>
                </div>
            </div>
            <div class="col-md-3">
                <label class="form-label">医生</label>
                <div class="position-relative">
                    <input type="text" id="doctorFilter" class="form-control" placeholder="输入医生姓名">
                    <div id="doctorSuggestions" class="position-absolute z-10 w-full bg-white border border-gray-300 rounded-b-lg shadow-lg max-h-60 overflow-y-auto d-none"></div>
                </div>
            </div>
            <div class="col-md-3">
                <label class="form-label">日期</label>
                <input type="text" id="dateFilter" class="form-control datepicker" placeholder="选择日期">
            </div>
            <div class="col-md-3">
                <label class="form-label">状态</label>
                <select id="statusFilter" class="form-select">
                    <option value="">全部状态</option>
                    <option value="1">可用</option>
                    <option value="0">不可用</option>
                </select>
            </div>
        </div>
        <div class="mt-3 text-end">
            <button class="btn btn-outline-primary" id="searchBtn">
                <i class="fas fa-search me-1"></i>搜索
            </button>
            <button class="btn btn-outline-secondary" id="resetBtn">
                <i class="fas fa-refresh me-1"></i>重置
            </button>
        </div>
    </div>

    <!-- 号源列表 -->
    <div class="table-container">
        <table class="table table-hover mb-0">
            <thead class="table-light">
            <tr>
                <th>科室</th>
                <th>医生</th>
                <th>日期</th>
                <th>时间段</th>
                <th>总号数</th>
                <th>剩余号数</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="scheduleTableBody">
            <tr>
                <td colspan="9" class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- 引入 Bootstrap JS -->
<!-- 引入 jQuery 和 Bootstrap JS -->
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<!-- 引入 Bootstrap Datepicker JS -->
<script src="/js/bootstrap-datepicker.min.js"></script>

<script>
    $(document).ready(function () {
        // 初始化日期选择器
        $('.datepicker').datepicker({
            format: 'yyyy-mm-dd', // 选择器格式
            todayHighlight: true,
            autoclose: true
        });


        // 格式化日期为 YYYY年MM月DD日 格式
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.getFullYear() + '-' +
                padZero(date.getMonth() + 1) + '-' +
                padZero(date.getDate()) ;
        }

        // 补零函数
        function padZero(num) {
            return num < 10 ? '0' + num : num;
        }

        // 获取号源数据并渲染表格
        function loadSchedules(departmentId, doctorId, date, status) {
            const params = {};
            if (departmentId) params.departmentId = departmentId;
            if (doctorId) params.doctorId = doctorId;
            if (date) params.date = date;
            if (status !== undefined && status !== '') params.status = status;

            $.get('/admins/getAllScheduleInfoOfDoctor', params, function (data) {
                const tbody = $('#scheduleTableBody');
                tbody.empty();

                if (!data || data.length === 0) {
                    tbody.append('<tr><td colspan="9" class="text-center">暂无号源数据</td></tr>');
                    return;
                }
                // 按日期升序排序
                data.sort((a, b) => {
                    const dateA = new Date(a.scheduleDate);
                    const dateB = new Date(b.scheduleDate);
                    return dateA - dateB;
                });
                data.forEach(schedule => {
                    const formattedDate = formatDate(schedule.scheduleDate);
                    const row = `
                        <tr>
                            <td>${schedule.departmentName}</td>
                            <td>${schedule.doctorName}</td>
                            <td>${formattedDate}</td>
                            <td>
                                <span class="period-badge">
                                    ${schedule.periodName}
                                </span>
                            </td>
                            <td>${schedule.totalNumber}</td>
                            <td>${schedule.availableNumber}</td>
                            <td>
                                <span class="status-badge ${schedule.status === '1' ? 'status-inactive' : 'status-active'}">
                                    ${schedule.status === '1' ? '不可用' : '可用'}
                                </span>
                            </td>
                            <td class="action-buttons">
                                <button class="btn btn-sm btn-warning edit-btn" data-id="${schedule.id}">
                                    <i class="fas fa-edit me-1"></i>修改
                                </button>
                                <button class="btn btn-sm btn-danger delete-btn" data-id="${schedule.id}">
                                    <i class="fas fa-trash-alt me-1"></i>删除
                                </button>
                            </td>
                        </tr>
                    `;
                    tbody.append(row);
                });
            }).fail(function () {
                $('#scheduleTableBody').append('<tr><td colspan="9" class="text-center text-danger">数据加载失败</td></tr>');
            });
        }

        loadSchedules();

        // 绑定刷新按钮事件
        $('#refreshBtn').click(function() {
            const departmentId = $('#departmentFilter').val();
            const date = $('#dateFilter').val();
            const status = $('#statusFilter').val();
            loadSchedules(departmentId, null, date, status);
        });




        // 搜索按钮点击事件
        $('#searchBtn').click(function() {
            // 获取日期选择器的值（YYYY-MM-DD格式）
            const dateValue = $('#dateFilter').val();

            // 创建纯日期字符串（不含时区）
            const pureDateStr = dateValue ? new Date(dateValue).toISOString().split('T')[0] : null;
            const filterParams = {
                departmentName: $('#departmentFilter').val() || null,
                doctorName: $('#doctorFilter').val() || null,
                scheduleDate: pureDateStr, // 使用纯日期格式
                status: $('#statusFilter').val() || null
            };
            searchSchedules(filterParams);
        });
        function searchSchedules(filterParams) {
            const tbody = $('#scheduleTableBody');
            tbody.empty();
            tbody.append(`
                <tr>
                    <td colspan="9" class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">搜索中...</span>
                        </div>
                    </td>
                </tr>
            `);

            console.log('Searching schedules with params:', filterParams);

            $.ajax({
                url: '/admins/searchScheduleInfo', // 使用搜索接口
                type: 'Post',
                contentType: 'application/json', // 明确设置内容类型为 JSON
                data: JSON.stringify(filterParams), // 将参数转换为 JSON 字符串
                success: function (data) {
                    console.log('Search results:', data);
                    tbody.empty();

                    if (!data || data.length === 0) {
                        tbody.append('<tr><td colspan="9" class="text-center">没有找到匹配的号源数据</td></tr>');
                        return;
                    }
                    // 按日期升序排序
                    data.sort((a, b) => {
                        const dateA = new Date(a.scheduleDate);
                        const dateB = new Date(b.scheduleDate);
                        return dateA - dateB;
                    });
                    data.forEach(schedule => {
                        const formattedDate = formatDate(schedule.scheduleDate);
                        const row = `
                            <tr>
                                <td>${schedule.departmentName}</td>
                                <td>${schedule.doctorName}</td>
                                <td>${formattedDate}</td>
                                <td>
                                    <span class="period-badge">
                                        ${schedule.period === 1 ? '上午' : '下午'}
                                    </span>
                                </td>
                                <td>${schedule.totalNumber}</td>
                                <td>${schedule.availableNumber}</td>
                                <td>
                                    <span class="status-badge ${schedule.status === 1 ? 'status-active' : 'status-inactive'}">
                                        ${schedule.status === 1 ? '可用' : '不可用'}
                                    </span>
                                </td>
                                <td class="action-buttons">
                                    <button class="btn btn-sm btn-warning edit-btn" data-id="${schedule.id}">
                                        <i class="fas fa-edit me-1"></i>修改
                                    </button>
                                    <button class="btn btn-sm btn-danger delete-btn" data-id="${schedule.id}">
                                        <i class="fas fa-trash-alt me-1"></i>删除
                                    </button>
                                </td>
                            </tr>
                        `;
                        tbody.append(row);
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.error('Error searching schedules:', textStatus, errorThrown, jqXHR.responseText);
                    tbody.empty();
                    tbody.append(`
                        <tr>
                            <td colspan="9" class="text-center text-danger">
                                搜索失败: ${textStatus} - ${errorThrown}
                            </td>
                        </tr>
                    `);
                }
            });
        }

        // 重置按钮点击事件
        $('#resetBtn').click(function() {
            $('#departmentFilter').val('');
            $('#doctorFilter').val('');
            $('#dateFilter').val('');
            $('#statusFilter').val('');
        });

        // 绑定修改按钮点击事件
        $(document).on('click', '.edit-btn', function() {
            const id = $(this).data('id');
            window.location.href = '/admins/updateSchedule?id=' + id;
        });

        // 绑定删除按钮点击事件
        $(document).on('click', '.delete-btn', function() {
            const id = $(this).data('id');
            if (confirm('确定要删除这个号源吗？')) {
                $.ajax({
                    url: `/admins/deleteSchedule/${id}`,
                    method: 'DELETE',
                    success: function() {
                        alert('删除成功');
                        const departmentId = $('#departmentFilter').val();
                        const doctorId = $('#doctorFilter').val();
                        const date = $('#dateFilter').val();
                        const status = $('#statusFilter').val();
                        loadSchedules(departmentId, doctorId, date, status);
                    },
                    error: function() {
                        alert('删除失败，请重试');
                    }
                });
            }
        });
    });
</script>

</body>
</html>